package org.example.component;

import lombok.extern.slf4j.Slf4j;
import org.example.config.SmsConfig;
import org.example.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
@Async("threadPoolTaskExecutor")
public class SmsComponent {

    /*发送地址*/
    private static final String url_Template = "https://jmsms.market.alicloudapi.com/sms/send?mobile=%s&templateId=%s&value=%s";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 发送验证码
     *
     * @param to         手机号
     * @param templateId 短信模板
     * @param value      验证码
     */
    public void send(String to, String templateId, String value) {

        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = String.format(url_Template, to, templateId, value);
        HttpHeaders headers = new HttpHeaders();
        //最后在header中的格式(中间是英⽂空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long endTime = CommonUtil.getCurrentTimestamp();
        log.info("耗时:{}ms,url={},body={}", endTime - beginTime, url, response.getBody());

        log.info("url={},body={}", url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信成功,响应信息:{}", response.getBody());
        } else {
            log.error("发送短信失败,响应信息:{}", response.getBody());
        }
    }
}
